/**
 * Created by tolya-yanot
 * Creation date:  09.05.13 21:38
 */
package {
import flash.display.Sprite;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display3D.Context3D;
import flash.events.Event;

[SWF(width="640", height="480", frameRate="60")]
public class WaterApp extends Sprite {
    private const swfWidth:int = 640;
    private const swfHeight:int = 480;

    private var context3D:Context3D;
    private var water:Water = new Water();

    public function WaterApp() {
        if (stage) {
            onAddedToStage();
        } else {
            addEventListener(Event.ADDED_TO_STAGE, onAddedToStage)
        }
    }

    private function onAddedToStage(event:Event = null):void {
        removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);

        stage.scaleMode = StageScaleMode.NO_SCALE;
        stage.align = StageAlign.TOP_LEFT;

        stage.stage3Ds[0].addEventListener(Event.CONTEXT3D_CREATE, onContext3DCreate);
        stage.stage3Ds[0].requestContext3D();
    }

    private function onContext3DCreate(event:Event):void {
        removeEventListener(Event.ENTER_FRAME, onEnterFrame);
        context3D = Stage3D(event.target).context3D;
        context3D.configureBackBuffer(swfWidth, swfHeight, 0, true);
        water.init(context3D, swfWidth, swfHeight, 500, 300);
        water.position.appendTranslation(0, 0.5, 0);
        addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }

    private function onEnterFrame(event:Event):void {
        context3D.clear(0.5, 0.5, 0.5);
        water.render(context3D);
        context3D.present();
    }
}
}
